package cloudLibrary;

import java.io.IOException;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/*
 * this class registers a user in the Users table of the database. 
 */

@SuppressWarnings("serial")
public class ItemDeletionServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null)
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI())); // demand
																				// user
																				// to
																				// be
																				// logged
																				// in.
		String itemID = "";
		String person = "";

		try {
			itemID = req.getParameter("itemID");
			person = req.getParameter("person");

		} catch (Exception e) {
			// ??
		}
		if (itemID == null || person == null) {
			resp.getWriter().println("person=" + person + "itemID" + itemID);
		} else {
			PersistenceManager pm = PMF.get().getPersistenceManager();

			try {			
				String query = "select from " + Item.class.getName()
						+ " where owner=='" + user.getEmail() + "'";//get all items i own
				List<Item> items = (List<Item>) pm.newQuery(query).execute();
				
				Key key = null;
				String itemTitle = null;
				long id = Long.parseLong(itemID.trim());
				for (Item i : items) {
					if (i.getItemID().getId() == id) {
						if (i.isReserved()){
							key = i.getItemID();
							itemTitle = i.getTitle();
						}
					}
				}
				if (key!=null){
				query = "select from " + Users.class.getName();
				List<Users> users = (List<Users>) pm.newQuery(query).execute();
				for (Users i : users) {
					
					if (i.getItems().contains(key)) {
					
						i.getItems().remove(key);
						resp.sendRedirect("/index.jsp?msg=returned&user=" + i.getName() + "&item=" + itemTitle);
					
					}
				}
				}

			} finally {
				pm.close();
			}
		}
	}

}
